package main

import (
	"fmt"
	"sync"
)

// Channel 的 ring buffer 实现？

// _ringBuff 环形缓冲区的结构体
type _ringBuffer struct {
	data  []interface{}
	head  int
	tail  int
	count int
	mutex sync.Mutex
}

// _newRingBuffer 创建一个新的环形缓冲区
func _newRingBuffer(size int) *_ringBuffer {
	return &_ringBuffer{
		data: make([]interface{}, size),
	}
}

// _Push 向环形缓冲区添加元素
func (rb *_ringBuffer) _Push(value interface{}) bool {
	rb.mutex.Lock()
	defer rb.mutex.Unlock()

	if rb.count == len(rb.data) {
		// 缓冲区满了
		return false
	}

	rb.data[rb.tail] = value
	fmt.Println("rb.tail:", (rb.tail+1)%len(rb.data))
	rb.tail = (rb.tail + 1) % len(rb.data)
	rb.count++
	return true
}

// _Pop 从环形缓冲区取出元素
func (rb *_ringBuffer) _Pop() (interface{}, bool) {
	rb.mutex.Lock()
	defer rb.mutex.Unlock()

	if rb.count == 0 {
		return nil, false
	}

	value := rb.data[rb.head]
	fmt.Println("rb.head:", (rb.head+1)%len(rb.data))
	rb.head = (rb.head + 1) % len(rb.data)
	rb.count--

	return value, true
}

// _isFull 判断缓冲区是否满
func (rb *_ringBuffer) _isFull() bool {
	return rb.count == len(rb.data)
}

// _isEmpty 判断缓冲区是否空
func (rb *_ringBuffer) _isEmpty() bool {
	return rb.count == 0
}

//func main() {
//	rb := _newRingBuffer(3)
//
//	fmt.Println(rb._Push(1))
//	fmt.Println(rb._Push(2))
//	fmt.Println(rb._Push(3))
//	fmt.Println(rb._Push(4))
//
//	for !rb._isEmpty() {
//		value, _ := rb._Pop()
//		fmt.Println(value)
//	}
//	fmt.Println(rb._Pop())
//}
